package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.ReleaseShopTypeEnum;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.product.ProductGroup;
import com.probox.common.entity.domain.product.vo.ProductGroupQuery;
import com.probox.common.entity.domain.product.vo.ProductGroupVo;
import com.probox.common.entity.mapper.product.ProductGroupMapper;
import com.probox.common.entity.query.BaseQuery;
import com.probox.common.entity.service.product.IProductGroupService;
import com.probox.common.entity.service.product.IProductInfoGroupService;
import com.probox.common.redis.service.RedisService;
import com.probox.product.api.domain.ProductGroupViewVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品分组信息Service业务层处理
 *
 * @date 2021-06-03
 */
@Service
@Transactional
public class ProductGroupServiceImpl extends ServiceImpl<ProductGroupMapper, ProductGroup> implements IProductGroupService {
    @Autowired
    private ProductGroupMapper productGroupMapper;

    @Autowired
    private IProductInfoGroupService iProductInfoGroupService;


    @Autowired
    private RedisService redisService;

    /**
     * 查询商品分组信息
     *
     * @param groupUid 商品分组信息ID
     * @return 商品分组信息
     */
    @Override
    public ProductGroupVo selectProductGroupById(Long groupUid) {
        ProductGroupVo groupVo = new ProductGroupVo();
        ProductGroup byId = this.getById(groupUid);
        if (ObjectUtil.isNotEmpty(byId)) {
            BeanUtils.copyProperties(byId, groupVo);
            //groupVo.setList(iProductInfoGroupService.queryGroupProductList(groupUid));
        }
        return groupVo;
    }

    /**
     * 获取商品分组信息已有的集合
     *
     * @param groupUid
     * @param type
     * @return
     */
    @Override
    public AjaxResult listByType(Long groupUid, String type) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code", 200);
        ajaxResult.put("msg", "操作成功");

        if (ReleaseShopTypeEnum.product.getKey().equals(type)) {
            ajaxResult.put("data", iProductInfoGroupService.queryGroupProductList(groupUid));
        } else if (ReleaseShopTypeEnum.service.getKey().equals(type)) {
            ajaxResult.put("data", iProductInfoGroupService.queryGroupItemList(groupUid));
        } else if (ReleaseShopTypeEnum.card.getKey().equals(type)) {
            ajaxResult.put("data", iProductInfoGroupService.queryGroupCardList(groupUid));
        }
        return ajaxResult;
    }

    @Override
    public List<ProductGroup> queryOtherCategoryList(){
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("GROUP_DEPTH", 0L);
        queryWrapper.gt("GROUP_UID", 3L);
        queryWrapper.orderByAsc("DATA_PRIORITY");
        return productGroupMapper.selectList(queryWrapper);
    }


    /**
     * 查询商品分组信息列表
     *
     * @param productGroup 商品分组信息
     * @return 商品分组信息
     */
    @Override
    public List<ProductGroup> queryList(ProductGroup productGroup) {
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productGroup.getGroupName())) && productGroup.getGroupName() != null) {
            queryWrapper.like("GROUP_NAME", productGroup.getGroupName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productGroup.getDataStatus())) && productGroup.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", productGroup.getDataStatus());
        }
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) {
            throw new BaseException("当前账号异常");
        }
        queryWrapper.eq("PLATFORM_UID", platformId);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (productGroup.getParentGroupUid() != null){
            queryWrapper.eq("PARENT_GROUP_UID", productGroup.getParentGroupUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productGroup.getDataPriority())) && productGroup.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }
        return productGroupMapper.selectList(queryWrapper);
    }


    /**
     * 新增商品分组信息
     *
     * @param productGroupVo 商品分组信息
     * @return 结果
     */
    @Override
    public boolean insertProductGroup(ProductGroupVo productGroupVo) {
        ProductGroup productGroup = new ProductGroup();
        BeanUtils.copyProperties(productGroupVo, productGroup);
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        DateTime date = DateUtil.date();
        productGroup.setPlatformUid(SecurityUtils.getPlatformId());
        productGroup.setCreateUid(userId);
        productGroup.setCreateName(username);
        productGroup.setCreateTime(date);
        productGroup.setUpdateUid(userId);
        productGroup.setUpdateName(username);
        productGroup.setUpdateTime(date);
        productGroup.setDataStatus(DataStatus.valid.getKey());
        productGroup.setDataPriority(1L);
        productGroup.setParentGroupUid(productGroupVo.getParentGroupUid());
        productGroup.setGroupDepth(productGroup.getGroupDepth());
        boolean save = this.save(productGroup);
        if (!save) throw new ProductException("添加失败,请稍后再试！");
        productGroupVo.setGroupUid(productGroup.getGroupUid());
        iProductInfoGroupService.insertProductInfoGroup(productGroupVo);
        return true;
    }

    /**
     * 修改商品分组信息
     *
     * @param productGroupVo 商品分组信息vo
     * @return 结果
     */
    @Override
    public boolean updateProductGroup(ProductGroupVo productGroupVo) {
        ProductGroup productGroup = new ProductGroup();
        BeanUtils.copyProperties(productGroupVo, productGroup);
        productGroup.setUpdateUid(SecurityUtils.getUserId());
        productGroup.setUpdateName(SecurityUtils.getUsername());
        productGroup.setUpdateTime(DateUtil.date());
        boolean b = this.updateById(productGroup);
        if (!b) throw new ProductException("修改失败,请稍后再试！");
        iProductInfoGroupService.updateProductInfoGroup(productGroupVo);
        redisService.deleteObject(CachePrefix.TEMPLATE_PRODUCT_GROUP + productGroup.getGroupUid());
        return true;
    }

    /**
     * 批量删除商品分组信息
     *
     * @param groupUids 需要删除的商品分组信息ID
     * @return 结果
     */
    @Override
    public boolean deleteProductGroupByIds(Long[] groupUids) {
        UpdateWrapper<ProductGroup> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("GROUP_UID", Arrays.asList(groupUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    private Integer queryName(String name, Long uid) {
        QueryWrapper<ProductGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BRAND_NAME", name);
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (uid != null) {
            queryWrapper.ne("BRAND_UID", uid);
        }
        return productGroupMapper.selectCount(queryWrapper);
    }


    /**
     * 用于前端查询商品分组信息
     *
     * @param productGroupQuery
     * @return
     */
    @Override
    public List<ProductGroupViewVo> selectGroup(ProductGroupQuery productGroupQuery) {
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productGroupQuery.getGroupName())) && productGroupQuery.getGroupName() != null) {
            queryWrapper.eq("GROUP_NAME", productGroupQuery.getGroupName());
        }
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.orderByDesc("UPDATE_TIME");
        List<ProductGroup> productGroups = productGroupMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productGroups)) return null;
        List<ProductGroupViewVo> list = new ArrayList<>();
        productGroups.forEach(vo -> {
            ProductGroupViewVo view = new ProductGroupViewVo();
            BeanUtils.copyProperties(vo, view);
            productGroupQuery.setGroupUid(view.getGroupUid());
            view.setList(iProductInfoGroupService.queryGroupProductView(productGroupQuery));
            list.add(view);
        });
        return list;
    }


    @Override
    public Integer selectGroupCount(ProductGroupQuery productGroupQuery) {
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productGroupQuery.getGroupName())) && productGroupQuery.getGroupName() != null) {
            queryWrapper.eq("GROUP_NAME", productGroupQuery.getGroupName());
        }
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.orderByDesc("UPDATE_TIME");
        List<ProductGroup> productGroups = productGroupMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productGroups)) return 0;
        return productGroups.size();
    }


    /**
     * 获取单个分组信息
     *
     * @param groupUid
     * @return
     */
    @Override
    public ProductGroupViewVo getGroupVo(Long groupUid) {
        String key = CachePrefix.TEMPLATE_PRODUCT_GROUP + groupUid;
        ProductGroupViewVo groupViewVo = redisService.get(key, ProductGroupViewVo.class);
        if (ObjectUtil.isEmpty(groupViewVo)) {
            groupViewVo = new ProductGroupViewVo();
            ProductGroup productGroup = productGroupMapper.selectById(groupUid);
            if (ObjectUtil.isEmpty(productGroup)) return groupViewVo;
            BeanUtils.copyProperties(productGroup, groupViewVo);
            ProductGroupQuery productGroupQuery = new ProductGroupQuery();
            productGroupQuery.setGroupUid(groupUid);
            groupViewVo.setList(iProductInfoGroupService.queryGroupProductView(productGroupQuery));
            redisService.set(key, groupViewVo, 30L, TimeUnit.MINUTES);
        }
        return groupViewVo;
    }

    @Override
    public List<ProductGroup> getGroupList(BaseQuery query) {
        String key = CachePrefix.PRODUCT_GROUP_LIST+query.getServiceType();
        List<ProductGroup> list = redisService.getCacheList(key);
        if (list == null || list.size() == 0) {
            QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            if (StringUtils.isNotEmpty(query.getServiceType())) {
                queryWrapper.like("SERVICE_TYPE", query.getServiceType());
            }
            queryWrapper.orderByAsc("DATA_PRIORITY");
            list = productGroupMapper.selectList(queryWrapper);
            for(ProductGroup g:list){
                if (StringUtils.isEmpty(g.getTipName())){
                    g.setTipName("");
                }
            }
            if (list.size()>0) {
                redisService.setCacheList(key, list);
            }
        }
        return list;
    }


    /**
     * 用于前端查询商品分组信息
     *
     * @param productGroupQuery
     * @return
     */
    @Override
    public List<ProductGroupViewVo> selectGroupP(ProductGroupQuery productGroupQuery) {
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productGroupQuery.getGroupName())) && productGroupQuery.getGroupName() != null) {
            queryWrapper.eq("GROUP_NAME", productGroupQuery.getGroupName());
        }
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.orderByDesc("UPDATE_TIME");
        List<ProductGroup> productGroups = productGroupMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productGroups)) return null;
        List<ProductGroupViewVo> list = new ArrayList<>();
        productGroups.forEach(vo -> {
            ProductGroupViewVo view = new ProductGroupViewVo();
            BeanUtils.copyProperties(vo, view);
            productGroupQuery.setGroupUid(view.getGroupUid());
            view.setList(iProductInfoGroupService.queryGroupProductView(productGroupQuery));
            list.add(view);
        });
        return list;
    }


    @Override
    public Integer selectGroupCountP(ProductGroupQuery productGroupQuery) {
        QueryWrapper<ProductGroup> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productGroupQuery.getGroupName())) && productGroupQuery.getGroupName() != null) {
            queryWrapper.eq("GROUP_NAME", productGroupQuery.getGroupName());
        }
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.orderByDesc("UPDATE_TIME");
        List<ProductGroup> productGroups = productGroupMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productGroups)) return 0;
        return productGroups.size();
    }

}
